package com.zhugang.week12;

/**
 * @program algorithms
 * @description: sortColors
 * @author: chanzhugang
 * @create: 2022/09/07 11:00
 */
public class SortColors2 {

    /**
     * 75 颜色分类
     * 双指针法
     *
     * @param nums
     */
    public void sortColors2(int[] nums) {
        // 0、1、2 三种颜色排序
        int p = 0;
        int q = nums.length - 1;
        while (p < q) {
            if (nums[p] != 2) {
                p++;
                continue;
            }
            if (nums[q] == 2) {
                q--;
                continue;
            }
            swap(nums, p, q);
            p++;
            q--;
        }

        int i = 0;
        int j = p;
        if (nums[j] == 2) {
            j--;
        }
        while (i < j) {
            if (nums[i] == 0) {
                i++;
                continue;
            }
            if (nums[j] == 1) {
                j--;
                continue;
            }
            swap(nums, i, j);
            i++;
            j--;
        }
    }

    private void swap(int[] nums, int p, int q) {
        int temp = nums[p];
        nums[p] = nums[q];
        nums[q] = temp;
    }
}